<?php
/**
 * Created by zhangyh.
 * User: zhangyh
 * Date: 2018/11/3
 * Time: 16:36
 */

namespace App\Service;


use App\Model\Member;
use  Illuminate\Support\Facades\Redis;

class WechatService extends BaseService
{


    public $app_id;
    public $app_secret;
    public $timeOut = 259200;

    /**
     * 小程序登陆获取openid
     * @author 张永辉 2018年11月3日
     */
    public function login()
    {
        $this->app_id     = config('app.app_id');
        $this->app_secret = config('app.app_secret');
        $url              = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->app_id . '&secret=' . $this->app_secret . '&js_code=' . $this->code . '&grant_type=authorization_code';
        $result           = jsonCurl($url);
        if (!empty($result['errcode'])) {
            $this->errCode = $result['errcode'];
            $this->errMsg  = $result['errmsg'];
            return $this->getReturn();
        }
        $memberData = Member::where('unionid', $result['unionid'])->first();
        //用户不存在
        if (!$memberData) {
            $memberData          = [
                'unionid' => $result['unionid'],
                'openid'  => $result['openid'],
            ];
            $id                  = Member::insertGetId($memberData);
            $this->data['token'] = $this->_getToken($id);
            return $this->getReturn();
        }
        //用户 已存在
        if ($memberData->openid != $result['openid']) {
            Member::where('id', $memberData->id)->update(['openid' => $result['openid']]);
        }
        $this->data['token'] = $this->_getToken($memberData->id);
        return $this->getReturn();
    }


    /**
     * 获取token
     * @param $input
     * @return mixed
     * @author 张永辉 2018年11月5日
     */
    private function _getToken($id)
    {
        $token = md5(uniqid('token', true));
        $key   = $this->getKey($token);
        if (Redis::EXISTS($key)) {
            return $this->_getToken();
        } else {
            $result = [
                'token' => $token,
                'mid'   => $id,
            ];
            Redis::SET($key, json_encode($result));
            Redis::EXPIRE($key, $this->timeOut);
            return $token;
        }
    }


    /**
     * 获取key
     * @param $input
     * @return mixed
     * @author 张永辉 2018年11月5日
     */
    public function getKey($token)
    {
        return 'token:' . $token;
    }


    /**
     *  更新用户信息
     * @author 张永辉 2018年11月5日
     */
    public function updataMember()
    {
        try {
            Member::where('id', $this->id)->update($this->data);
        } catch (\Exception $e) {
            \Log::info('用户服务授权错误' . $e->getMessage());
            $this->errCode = 10020;
            $this->errMsg  = $e->getMessage();
            return $this->getReturn();
        }
    }


    /**
     * token是否过期
     * @author 张永辉 2018年11月5日
     */
    public function isTokenExpire()
    {
        return Redis::EXISTS($this->getKey($this->token));
    }


    /**
     * 获取token信息
     * @param $token
     * @param array $field
     * @return array|mixed
     * @author 张永辉 2018年11月15日
     */
    public function getTokenData()
    {
        if (empty($this->token)) {
            $this->errCode = 10021;
            $this->errMsg  = 'token不能为空';
            return $this->getReturn();
        }
        $key    = $this->getKey($this->token);
        $result = Redis::GET($key);
        if (!$result) {
            $this->errCode = 10021;
            $this->errMsg  = 'token不存在或已过期';
            return $this->getReturn();
        }
        Redis::EXPIRE($key, $this->timeOut);
        $result = json_decode($result, true);
        if (!empty($this->field)) {
            $this->data = [];
            foreach ($this->field as $item) {
                $this->data[$item] = array_column($result, $item);
            }
            return $this->getReturn();
        } else {
            $this->data = $result;
            return $this->getReturn();
        }


    }



}